package gretha.donnees;

import gretha.utils.ConnecteurBDD;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class Massif {
	
	private String nom;
	
	private ArrayList<CohorteDuMassif> cohortes;
	
	public Massif() {
		cohortes = new ArrayList<CohorteDuMassif>();
	}

	public Massif(ArrayList<CohorteDuMassif> c) {
		cohortes = c;
	}
	
	public void sauvegarderEnBDD()
	{
		try {
			ConnecteurBDD.executeUpdate("INSERT INTO massifs (nom) VALUES ('"+nom+"')");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		int idMassif = getId();
		
		for(CohorteDuMassif cm : cohortes)
		{
			cm.sauvegardeEnBDD(idMassif);
		}
	}
	
	
	public int getId() {
		int retour = -1;
		try {
			ResultSet rs = ConnecteurBDD.executeQuery("SELECT idMassif from massifs WHERE nom='"+nom+"'");
			rs.next();
			retour = rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return retour;
	}

	public void recupererDonnees(int idMassif) {
		//Recuperation du nom
		try {
			ResultSet rs = ConnecteurBDD.executeQuery("SELECT nom from massifs where idMassif ="+idMassif);
			rs.next();
			setNom(rs.getString(1));
		} catch (SQLException e) {
			e.printStackTrace();
		}	
		
		//Recuperation des cohortes
		try {
			ResultSet rs = ConnecteurBDD.executeQuery("SELECT * from contenancemassif CM WHERE CM.idMassif ="+idMassif);
			ArrayList<CohorteDuMassif> cohortesLiees = new ArrayList<CohorteDuMassif>();
			while(rs.next())
			{
				int idCohorte = rs.getInt(2);
				int quantite = rs.getInt(3);
				int age = rs.getInt(4);
				int numeroDeParcelle = rs.getInt(5);
				
				Cohorte tmp = new Cohorte();
				tmp.recupererDonnees(idCohorte);
				
				CohorteDuMassif cohorteTmp = new CohorteDuMassif(tmp, quantite, age, numeroDeParcelle);
				cohortesLiees.add(cohorteTmp);
			}
			this.cohortes = cohortesLiees;
				
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		
	}
	
	public static void supprimerMassifEnBDD(int idMassif)
	{
		try {
			ConnecteurBDD.executeUpdate("DELETE FROM massifs WHERE idMassif = "+idMassif);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * 			GET and SET
	 */
	
	public ArrayList<CohorteDuMassif> getCohortes() {
		return cohortes;
	}
	public void setCohortes(ArrayList<CohorteDuMassif> cohortes) {
		this.cohortes = cohortes;
	}
	
	public String getNom() {
		return nom;
	}

	public void setNom(String nom) {
		this.nom = nom;
	}
	
	
}
